const COPY = 'copy'
const COPIED = 'copied'
function codeCopy() {
    if (typeof document === 'undefined') return; // 解决 document is not defined 的bug
    const preCode = document.querySelectorAll('pre code');
    if(!preCode) return
    Array.prototype.forEach.call(preCode, function(item) {
        const spanEl = document.createElement("span");
        spanEl.className = 'code-copy';
        spanEl.innerText = COPY;
        item.parentNode.setAttribute('class','copy-box');
        item.parentNode.appendChild(spanEl)
    })
    //markdown 代码存放在pre code 标签对中
    const codeCopyHandler = document.querySelectorAll('pre.copy-box .code-copy')
    Array.prototype.forEach.call(codeCopyHandler, function(itemCopyBox) {
        itemCopyBox.onclick = function (el) {
            if(el.target.innerText === COPIED) return;
            let text = el.target.previousSibling.textContent || el.target.previousSibling.value;
            const textareaEl = document.createElement("textarea");
            textareaEl.textContent = text;
            document.body.appendChild(textareaEl)
            textareaEl.select();
            document.execCommand('Copy',true)
            textareaEl.remove()
            el.target.innerText = COPIED
            setTimeout(() => {
                el.target.innerText = COPY
            },1000)
        }
    })
}

export default codeCopy;
